<template>
  <div class="outbound-call-line">
    <div class="tool">
      <div class="pag-wapper">
        <span @click.stop="fetchData" class="refresh margin-l-10"><i class="iconfont icon-shuaxin"></i><span>刷新</span></span>
      </div>
    </div>
    <div class="table-wapper">
      <el-table
        :data="list"
        size="mini"
        highlight-current-row
        stripe
        style="width: 100%">
        <el-table-column label="线路类型" width="150"><template scope="scope">{{ scope.row.TypeName }}</template></el-table-column>
        <el-table-column label="中继号号段及运营商"><template scope="scope">{{ scope.row.LineName }}</template></el-table-column>
        <el-table-column label="外显号" width="180" :show-overflow-tooltip="true"><template scope="scope">{{ scope.row.MultiDidEnable ? scope.row.MultiDidNum : scope.row.DidNum }}</template></el-table-column>
        <el-table-column label="最后更新时间" width="150"><template scope="scope">{{ scope.row.UpdateTime }}</template></el-table-column>
        <el-table-column label="操作" width="100">
          <template scope="scope"><el-button type="text" size="small" @click="handleEdit(scope.row)">{{$t('public.edit')}}</el-button></template>
        </el-table-column>
      </el-table>
    </div>
    <leftSlide :visible.sync='slideLeft' title="修改外呼线路" @saveClick="handleSaveCLick" @cancelClick="cancelClick" :showFooter="true">
      <div style="margin: 20px">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm" labelPosition="top">
          <el-form-item label="机柜：" prop="Board">
            <el-select v-model="form.Board" placeholder="请选择" class="select-width" @change="changeBoard" filterable>
              <el-option v-for="(item,index) in boardList" :key="index" :label="item.name" :value="item._id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="外呼路由：" prop="Exten">
            <el-select v-model="form.Exten" placeholder="请选择" filterable class="select-width">
              <el-option v-for="(item,index) in lineList" :key="index" :label="item.name" :value="item.number"></el-option>
            </el-select>
          </el-form-item>
          <div v-if="currentObj.Dialout === true || currentObj.Dialout === 'true'">
            <el-form-item label="启用多外显号码：" prop="MultiDidEnable">
              <el-radio-group v-model="form.MultiDidEnable">
                <el-radio :label="true">启用</el-radio>
                <el-radio :label="false">不启用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="多外显号应用范围：" prop="MultiDidScope" v-show="form.MultiDidEnable === true || form.MultiDidEnable === 'true'">
              <el-radio-group v-model="form.MultiDidScope">
                <el-radio label="all">全部</el-radio>
                <el-radio label="hand">手拨外呼</el-radio>
                <el-radio label="auto">批量外呼</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="外显策略：" prop="MultiDidStrategy"  v-show="form.MultiDidEnable === true || form.MultiDidEnable === 'true'">
              <el-radio-group v-model="form.MultiDidStrategy">
                <el-radio label="order">配置顺序</el-radio>
                <el-radio label="random">随机顺序</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="多外显号码内容：" prop="MultiDidNum"  v-if="form.MultiDidEnable === true || form.MultiDidEnable === 'true'">
              <el-input type="textarea" v-model="form.MultiDidNum"></el-input>
            </el-form-item>
            <div class="prompt margin-t-15" v-if="form.MultiDidEnable === true || form.MultiDidEnable === 'true'">温馨提示 多外显号码可以配置多个单独号码和号码段以英文逗号分割，号码段以中划线分割。
例如：01053500303,01053500000-01053509999,0105377010</div>
          </div>
          <el-form-item label="外显号码：" prop="DidNum"  v-if="(!currentObj.Dialout|| currentObj.Dialout === 'false') || (!form.MultiDidEnable || form.MultiDidEnable === 'false')">
            <el-input v-model="form.DidNum"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </leftSlide>
  </div>
</template>
<script>
//  import {getCache} from '@/utils/m7Utils.js'
  import leftSlide from '@/components/ui-modules/newConfig/leftSlide.vue'
  export default {
    name: 'outboundCallLine',
    data () {
      return {
        rules: {
          DidNum: [{ required: true, message: '请输入外显号码', trigger: 'blur' }],
          MultiDidNum: [{ required: true, message: '请输入多外显号内容', trigger: 'blur' }],
          Exten: [{ required: true, message: '请选择外呼路由', trigger: 'change' }],
          Board: [{ required: true, message: '请选择机柜', trigger: 'change' }]
        },
        form: {},
        slideLeft: false,
        list: [],
        currentObj: {},
        boardList: [],
        lineList: [],
        oldPBX: ''
      }
    },
    components: {
      leftSlide
    },
    watch: {
      pbx () {
        let routerName = this.$route.meta.title
        if (routerName === 'outboundCallLine') {
          console.log('outbound')
          this.fetchData()
        }
      }
    },
    computed: {
      pbx () {
        return this.$store.state.config.callCenter.currentPBX
      }
    },
    methods: {
      handleServiceData () {
        if (this.currentObj.Dialout === 'true' || this.currentObj.Dialout === true) {
          if (this.form.MultiDidEnable === 'true' || this.form.MultiDidEnable === true) {
            if (this.form.MultiDidNum === '') {
              this.$message.error('启用多外显号，必须输入多外显号内容！')
              return false
            }
          }
          if (this.form.MultiDidNum !== '') {
            var reg = /^[0-9,-]+$/
            if (!reg.test(this.form.MultiDidNum)) {
              this.$message.error('多外显号内容号码有误！')
              return false
            }
          }
        }
        if (this.form.Board === '') {
          this.$message.error('请选择机柜')
          this.form.Exten = ''
          return false
        }
        let BoardName = ''
        for (let i = 0; i < this.boardList.length; i++) {
          if (this.form.Board === this.boardList[i]._id) {
            BoardName = this.boardList[i].name1
            break
          }
        }
        if (this.currentObj.Dialout === 'true' || this.currentObj.Dialout === true) {
          let data = {
            _id: this.currentObj._id,
            Dialout: this.currentObj.Dialout + '',
            Board: this.form.Board,
            Exten: this.form.Exten,
            BoardName: BoardName,
            DidNum: this.form.DidNum,
            MultiDidEnable: this.form.MultiDidEnable + '',
            MultiDidScope: this.form.MultiDidScope,
            MultiDidStrategy: this.form.MultiDidStrategy,
            MultiDidNum: this.form.MultiDidNum,
            Account: this.currentObj.Account || this.$store.state.session.user.account,
            PBX: this.currentObj.PBX || this.pbx
          }
          this.handleEditData(data)
        } else {
          let data = {
            _id: this.currentObj._id,
            Dialout: this.currentObj.Dialout + '',
            Board: this.form.Board,
            Exten: this.form.Exten,
            BoardName: BoardName,
            DidNum: this.form.DidNum,
            Account: this.currentObj.Account || this.$store.state.session.user.account,
            PBX: this.currentObj.PBX || this.pbx
          }
          this.handleEditData(data)
        }
      },
      handleSaveCLick () {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[this.pbx]) {
              if (this.$store.state.session.ivrMap[this.pbx].data.ivr_service_no) {
                let isMayServiceNo = false
                for (let i = 0; i < this.$store.state.session.ivrMap[this.pbx].data.ivr_service_no.length; i++) {
                  if (this.$store.state.session.ivrMap[this.pbx].data.ivr_service_no[i].Exten.indexOf(this.form.DidNum) !== -1) {
                    isMayServiceNo = true
                  }
                }
                if (!isMayServiceNo) {
                  this.$confirm('这个外显号码不是您账户的服务号，确认要配置为外显号码吗？', this.$t('public.tip'), {
                    confirmButtonText: this.$t('public.confirm'),
                    cancelButtonText: this.$t('public.cancel'),
                    cancelButtonClass: 'primary_btn',
                    confirmButtonClass: 'primary_btn',
                    type: 'warning'
                  }).then(() => {
                    this.handleServiceData()
                  })
                } else {
                  this.handleServiceData()
                }
              } else {
                this.handleServiceData()
              }
            } else {
              this.handleServiceData()
            }
          }
        })
      },
      handleEditData (data) {
        let action = 'updateLine'
        if (this.currentObj.LineFlag === '1' || this.currentObj.LineFlag === 1) {
          data.LineFlag = '1'
          action = 'saveSmallNumDialLine'
        }
        this.$store.dispatch(action, data).then((res) => {
          if (res.success) {
            this.$message.success('修改成功')
            this.cancelClick()
            this.fetchData()
          }
        })
      },
      cancelClick () {
        this.slideLeft = false
      },
      changeBoard (board) {
        this.form.Exten = ''
        this.getLineList(board)
      },
      fetchData () {
        this.$store.dispatch('queryOutLine', {Account: this.$store.state.session.account.account, PBX: this.pbx}).then(resp => {
          if (resp && resp.success) {
            this.$store.commit('SET_IVRMAP_DETAIL', {PBX: this.pbx, typeName: 'ivr_line', data: resp.list || [], flag: 'data', node: this})
            this.handleData(resp.list)
          }
        })
      },
      handleData (ivrLine) {
        this.list = []
        if (ivrLine.length !== 0) {
          for (let i = 0; i < ivrLine.length; i++) {
            let _obj = ivrLine[i]
            if (_obj.Exten) {
              _obj.DisplayName = _obj.Exten
            } else {
              _obj.DisplayName = '未配置线路'
              _obj.UpdateTime = ''
              _obj.DidNum = ''
            }
            if (_obj.Dialout) {
              _obj.TypeName = '外呼线路'
              if (_obj.LineFlag === 1 || _obj.LineFlag === '1') {
                _obj.TypeName = '小号外呼线路'
              }
            } else {
              _obj.TypeName = '呼转线路'
            }
            _obj.TypeName1 = this.getTypeName(_obj.Dialout, _obj.LineFlag)
            _obj.LineName = this.getLineName(_obj.Board, _obj.Exten)
            this.list.push(_obj)
          }
        }
      },
      initData () {
        if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[this.pbx]) {
          let ivrLine = this.$store.state.session.ivrMap[this.pbx].data.ivr_line
          this.handleData(ivrLine)
        }
      },
      getLineName (board, line) {
        let boardMap = this.$getCache('line')
        if (line !== 'Exten') {
          if (board !== 'Board') {
            if (boardMap[board] && boardMap[board].routes) {
              let routes = boardMap[board].routes
              for (let i = 0; i < routes.length; i++) {
                if (line === routes[i].number) {
                  return routes[i].name + '(机柜:' + boardMap[board].name + ')'
                }
              }
              return '未配置线路'
            }
          } else {
            let text = '未配置线路'
            for (let key in boardMap) {
              if (boardMap[key].routes) {
                for (let i = 0; i < boardMap[key].routes.length; i++) {
                  if (line === boardMap[key].routes[i].number) {
                    text = boardMap[key].routes[i].name
                  }
                }
              }
            }
            return text
          }
        } else {
          return '未配置线路'
        }
      },
      getTypeName (type, flag) {
        if (type === 'true' || type === true) {
          if (flag === '1' || flag === 1) {
            return '小号外呼线路'
          }
          return '外呼线路'
        } else {
          return '呼转线路'
        }
      },
      getBoardList (board, exten) {
        let boardMap = this.$getCache('line')
        console.log(boardMap)
        this.boardList = []
        for (let key in boardMap) {
          this.boardList.push({_id: key, name1: boardMap[key].name, name: boardMap[key].name + '(归属地:' + boardMap[key].location + ')'})
        }
      },
      getLineList (board) {
        let boardMap = this.$getCache('line')
        this.lineList = []
        for (let key in boardMap) {
          if (board === key) {
            if (boardMap[key].routes) {
              this.lineList = boardMap[key].routes
            } else {
              this.lineList = []
            }
          }
        }
      },
      handleEdit (row) {
        this.slideLeft = true
        this.$refs['form'].resetFields()
        this.currentObj = row
        this.form = {
          Board: row.Board || '',
          Exten: row.Exten || '',
          DidNum: row.DidNum || '',
          MultiDidEnable: row.MultiDidEnable || false,
          MultiDidScope: row.MultiDidScope || 'all',
          MultiDidStrategy: row.MultiDidStrategy || 'order',
          MultiDidNum: row.MultiDidNum || ''
        }
        this.getLineList(row.Board, row.Exten)
      }
    },
    deactivated () {
      this.oldPBX = this.pbx
    },
    activated () {
      if (this.oldPBX !== this.pbx) {
        this.fetchData()
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', {type: 'line'}).then(() => {
        this.fetchData()
        this.getBoardList()
      })
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .outbound-call-line
    margin 20px
    overflow-y hidden
    display: flex;
    -ms-flex-direction: column;
    flex-direction: column;
    overflow-y: auto;
    font-size: 12px;
    .prompt
      color $c-prompt
    .margin-l-10
      margin-left 10px
    .select-width
      width 200px
    .margin-t-15
      margin-top 15px
    .refresh
      color $c-main
      padding-right 15px
      cursor pointer
    .wapper
      display flex
      flex-direction column
    .tool
      border 1px solid #e7e7eb
      border-bottom 0
      padding  15px 0px
      /*display flex*/
      justify-content space-between
</style>

